import 'dart:async';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/utils/wifi/wifi_utils.dart';
import 'package:casdon/modules/device/application/notification/device_discovery_provider.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

class DeviceDiscoveriedListWidget extends ConsumerStatefulWidget {
  const DeviceDiscoveriedListWidget({super.key});

  @override
  ConsumerState<DeviceDiscoveriedListWidget> createState() =>
      _DeviceDiscoveriedListWidgetState();
}

class _DeviceDiscoveriedListWidgetState
    extends ConsumerState<DeviceDiscoveriedListWidget> {
  StreamSubscription<ThingSmartDeviceModel>? _subscription;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final discoveryState = ref.watch(deviceDiscoveryProvider);
    final isSearchingState = ref.watch(isSearchingProvider);
    final errorState = ref.watch(discoveryErrorProvider);
    final devices = discoveryState.devices;
    final showAll = ref.watch(_showAllProvider);

    if (isSearchingState && devices.isEmpty) {
      return _buildLoading();
    }

    if (errorState != null) {
      return _buildError(errorState);
    }

    return _buildDeviceList(ref, devices, showAll);
  }

  Widget _buildLoading() {
    return const SizedBox.shrink();
  }

  Widget _buildError(Object error) {
    return Center(child: Text(''));
  }

  Widget _buildDeviceList(
    WidgetRef ref,
    List<ThingSmartDeviceModel> devices,
    bool showAll,
  ) {
    if (devices.isEmpty) return SizedBox.shrink();
    final displayCount = showAll ? devices.length : min(4, devices.length);
    final rowCount = (displayCount / 2).ceil();
    final shouldShowMore = devices.length > 4;

    return ColoredBox(
      color: Colors.white,
      child: Column(
        children: [
          // 核心网格布局（添加点击反馈）
          SizedBox(
            height: 80.h * rowCount + 24.h,
            child: GridView.builder(
              physics: const NeverScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 8.w),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8.w,
                mainAxisSpacing: 8.h,
                childAspectRatio: _calculateAspectRatio(ref.context),
              ),
              itemCount: displayCount,
              itemBuilder: (ctx, index) {
                Log.i("构建设备项: ${devices[index].name}");
                return GestureDetector(
                  onTap: () => _handleDeviceTap(ref, devices[index]), // 点击事件
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: _buildDeviceItem(devices[index]),
                  ),
                );
              },
            ),
          ),

          // 显示更多按钮
          if (shouldShowMore) _buildMoreButton(ref, showAll, devices.length),
        ],
      ),
    );
  }

  double _calculateAspectRatio(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final itemWidth = (screenWidth - 24.w - 8.w) / 2; // 计算实际项目宽度
    return itemWidth / 80.h; // 宽高比 = 宽度/固定高度
  }

  Widget _buildDeviceItem(ThingSmartDeviceModel device) {
    return SizedBox(
      height: 80.h, // 严格限制高度
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Padding(
          padding: EdgeInsets.all(8.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 左侧图片区域
              Container(
                width: 45.w,
                height: 45.h,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                padding: EdgeInsets.all(4.w),
                child: CachedNetworkImage(
                  imageUrl: device.iconUrl,
                  placeholder: (_, __) => _buildPlaceholder(),
                  errorWidget: (_, __, ___) => _buildErrorIcon(),
                  fit: BoxFit.contain,
                ),
              ),

              SizedBox(width: 8.w),

              // 右侧文字区域
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _formatDeviceName(device.name),
                      style: context.textTheme.bodyMedium!.copyWith(
                        color: context.customColorThemeNonNull.textColor1,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 4.h),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPlaceholder() {
    return Icon(Icons.image, size: 24.r, color: Colors.grey[300]);
  }

  Widget _buildErrorIcon() {
    return Icon(Icons.broken_image, size: 24.r, color: Colors.grey[400]);
  }

  Widget _buildMoreButton(WidgetRef ref, bool showAll, int totalCount) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h, top: 8.h),
      child: TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
        ),
        onPressed: () => ref.read(_showAllProvider.notifier).state = !showAll,
        child: Text(
          showAll ? '收起' : '显示更多 ($totalCount个设备)',
          style: TextStyle(
            fontSize: 14.r,
            color: Theme.of(ref.context).primaryColor,
          ),
        ),
      ),
    );
  }

  String _formatDeviceName(String? name) {
    const prefix = '凯度';
    final safeName = name ?? '';
    if (safeName.startsWith(prefix)) {
      return safeName.substring(prefix.length).trimLeft();
    }
    return safeName;
  }
}

Future<({String? ssid, String? password})> checkWifiInfo() async {
  final ssidResult = await WifiUtils.getInstance().getCurrentWifiSsidResult();
  if (!ssidResult.hasPermission) {
    ToastUtil.show("请开启定位权限后再尝试");
    return (ssid: null, password: null);
  }
  final ssid = ssidResult.ssid;
  if (ssid == null) {
    return (ssid: null, password: null);
  }
  final spUnit = await SPUtils.getInstance();
  final pwd = spUnit.getString(ssid);
  if (pwd.isEmpty) {
    return (ssid: null, password: null);
  }
  return (ssid: ssid, password: pwd);
}

void _handleDeviceTap(WidgetRef ref, ThingSmartDeviceModel device) async {
  Log.i('点击了设备: ${device.name}');
  // final wifiInfo = await checkWifiInfo();
  // if (ref.context.mounted == false) return;
  // if (wifiInfo.ssid == null) {
  //   WifiConfigRoute(
  //     pid: device.productId,
  //     deviceName: device.name,
  //     nextRoute: "device_pairnet_list",
  //   ).push(ref.context);
  //   return;
  // }
  PairnetListRoute().push(ref.context);
}

final _showAllProvider = StateProvider<bool>((ref) => false);
